/*
 *  Class name: TeamDataModel.java
 *  Version: 1.0
 *  Date: 21.11.2013
 */
package cz.muni.fi.pa165.soccergamesarchive.datamodels.entity;

import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.TeamDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.services.TeamServiceBeanLocal;
import cz.muni.fi.pa165.soccergamesarchive.datamodels.EntityDataModel;
import java.util.List;
import java.util.Objects;

import static java.lang.Integer.toUnsignedLong;
import static java.lang.Long.parseLong;

/**
 *
 * @author Martin
 */
public class TeamDataModel extends EntityDataModel<TeamDTO> {

    private final TeamServiceBeanLocal teamServiceBean;

    public TeamDataModel(TeamServiceBeanLocal teamServiceBean) {
        this.teamServiceBean = teamServiceBean;
    }

    @Override
    protected List<TeamDTO> getArrangedList(int offset, int limit) {
        return teamServiceBean.getLimitedNumberOfTeams(offset, limit,
                getCompleteFilterMap(), getOrderMap());
    }

    @Override
    protected int getAllArrangedItemsCount() {
        return teamServiceBean.getFilteredTeamsCount(getCompleteFilterMap());
    }

    @Override
    protected TeamDTO getEntityByID(Object id) {

        TeamDTO team = null;
        Long key;

        if (id instanceof String) {
            key = parseLong((String) id);
        } else if (id instanceof Long) {
            key = (Long) id;
        } else if (id instanceof Integer) {
            key = toUnsignedLong((int) id);
        } else {
            //TODO: CHANGE TO LOGGER
            System.err.println(getClass().getSimpleName()
                    + "->getEntityByID->"
                    + "ID has uncorrect type: "
                    + "ID value: " + id);
            return null;
        }

        for (TeamDTO teamItem : dataList) {

            if (Objects.equals(teamItem.getId(), key)) {
                team = teamItem;
                break;
            }
        }

        if (team == null) {
            team = teamServiceBean.getTeamById(key);
        }

        return team;
    }

    @Override
    protected Long getID(TeamDTO entity) {
        return entity.getId();
    }

}
